<template>
	<div class="content">
		<div class="main">
			<!-- 第一个tabs 基本信息 药典 -->
			<el-dialog title="编辑西成药目录" :visible.sync="dialogFormVisible" width="68%" :before-close="handleAddClose">
			<!-- Main -->
			<el-tabs type="border-card">
			  <el-tab-pane label="基本信息[F2]">
				<!-- 表单 -->
				<el-form ref="form" :rules="addRules" :model="editForm" size="mini">
					<el-row :gutter="20">
						<el-col :span="v.spanRows" type="flex" v-for="(v,i) in formType" :key="i">
						  <!-- select -->
						  <el-form-item v-if="v.type == 'select'" :label="v.label" :prop="v.prop">
							<el-select v-model="$data.editForm[v.modelValue]" :disabled="v.disabled ? addDisabled : v.disabled" filterable
							placeholder="请选择" @focus="handlefoucs(v,i)" @change="handleChange" @input="inputSearch(v,i)"
							:filter-method="searchMethod"
							:popper-append-to-body="false">
							<el-option v-for="item in $data[v.op]" :key="item.id" :label="item.label" :value="item.id">
								<div class="option-item" style="display: flex;flex-direction: column;">
									<span>{{ item.label }}</span>
									<span style="font-size: 12px;color: #b4b4b4;">{{ item.licensorChinese }}</span>
								</div>	
							</el-option>
							</el-select>
						  </el-form-item>
						  <!-- input -->
						  <el-form-item v-if="v.type == 'input'" :label="v.label" :prop="v.prop">
							<el-input v-model="$data.editForm[v.modelValue]" :disabled="v.disabled" @blur="inputChance(v,i)"></el-input>
						  </el-form-item>
						  <!-- checked -->
						  <el-form-item v-if="v.type == 'checked'" :label="v.label">
							<el-checkbox v-model="$data.editForm[v.modelValue]"></el-checkbox>
						  </el-form-item>
						  <!-- textarea -->
						  <el-form-item v-if="v.type == 'textarea'" :label="v.label">
							<el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="$data.editForm[v.modelValue]"></el-input>
						  </el-form-item>
						  <!-- 新增厂家信息 -->
						  <el-form-item v-if="v.type == 'table'" :label="v.label">
							<div class="table">
								<div style="display: flex;justify-content: space-between;background: #00557f;align-items: center;">
									<span style="font-size: 12px;color: #fff;"></span>
									<li style="list-style-type: none;margin-right: 12px;"><el-button v-for="(v,i) in boxaBtn" :key="i" :type="v.type"
									 :icon="v.icon" size="medium" @click="boxaBtnHandClick(i)"></el-button></li>
								</div>
								<el-table :data="ManufacturerData" border align="center" style="width:828px;">
									<el-table-column fixed="left" label="行号" type="index" width="48"></el-table-column>
									<el-table-column v-for="(col, inx) in ManufacturerDataRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name"></el-table-column>
								</el-table>
							</div>
						  </el-form-item>
						</el-col>
					</el-row>
				</el-form>
			  </el-tab-pane>
			  <el-tab-pane label="药品说明[F3]">
				<!-- 表单 -->
				<el-form ref="editForm" :rules="addRules" :model="editForm" size="mini" label-width="88px">
					<el-row :gutter="20">
						<el-col :span="v.spanRows" type="flex" v-for="(v,i) in formType" :key="i">
						  <!-- textarea -->
						  <el-form-item v-if="v.type == 'textarea2'" :label="v.label">
							<el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="$data.editForm[v.modelValue]"></el-input>
						  </el-form-item>
						</el-col>
					</el-row>
				</el-form>
			  </el-tab-pane>
			  <el-tab-pane label="使用注意[F4]">
				  <!-- 表单 -->
					<el-form ref="editForm" :rules="addRules" :model="editForm" size="mini" label-width="88px">
						<el-row :gutter="20">
							<el-col :span="v.spanRows" type="flex" v-for="(v,i) in formType" :key="i">
							  <!-- textarea -->
							  <el-form-item v-if="v.type == 'textarea3'" :label="v.label">
								<el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="$data.editForm[v.modelValue]"></el-input>
							  </el-form-item>
							</el-col>
						</el-row>
					</el-form>
			  </el-tab-pane>
			  
			</el-tabs>
			<div slot="footer" class="dialog-footer">
				<el-button size="mini" type="primary" @click="editNewDiction">修改</el-button>
				<el-button size="mini" @click="dialogFormVisible = false">取消</el-button>
			</div>
			</el-dialog>
		</div>
		<div class="feet">
			<!--  编辑 厂家模态框 -->
			<editDialogManufacturer ref="editComponent" @editManufacturer="editManufacturer" :param="param"></editDialogManufacturer>
		</div>
	</div>
</template>

<script>
	// selfs / props
	import addDialogManufacturer from './Manufactur/addDialogManufacturer.vue'
	import editDialogManufacturer from './Manufactur/editDialogManufacturer.vue'
	// selfs / js
	import editForm from './editForm.js' //Form表单
	import addDialogType from './addDialogType.js' //Form表单
	import Pinyin from "@/external/pinyin.js"; //中译音
	// axios
	import {
		getDInfo,getDrugUnt,getDosaUnt,updateDrugInformation,getMedicationFrequency,getMedicationWay,getEisai,getMedcas,getDInfos,
		ProductNameCode,getDrugType,selectDrugDosageForm,addDrugs,
		selectCateGory,selectOneCateGory,selectTwoCateGory,selectThreeCateGory,
		selectDocVtByType,getRecordCategory,
	} 
	from "@/api/MedicenCata.js";
	export default {
		inject: ['reload'], // 无痕刷新
		components: {
			addDialogManufacturer,editDialogManufacturer
		},
		data() {
			return {
				// str
				idcode:'', //参数储存 IdCode
				idcodeIII:'', //参数储存 IdCode
				addDialogManufacturer:false,
				getValue:'',
				inputSearchValue:'',
				// number
				idx:0,
				pageNum: 1, //当前页currentPage
				pageSize: 88, //每页展示条数
				totalSize: 10, //总条数
				// blean
				dialogFormVisible:false, // model
				cascaderdisabled:false, //禁用
				selectdisabled:false, //禁用
				disabledKss:true,
				addDisabled:true,
				
				switchValue:false,
				
				newData:[],
				// arr
				formType:[],
				options:[],
				NameOptions:[],
				itemsForObj:[],
				YNoptions:[{id:1,label:'是',value:'是'},{id:0,label:'否',value:'否'}],
				statusOption:[{id:1,label:'可用',value:'可用'},{id:2,label:'锁定',value:'锁定'}],
				saleUntOption:[{id:1,label:'最小单位',value:'最小单位'},{id:2,label:'包装单位',value:'包装单位'}],
				antcLvOption:[ // 抗生素等级
					{ id:1,label:'一级抗生素(非限制使用)',value:'一级抗生素(非限制使用)'},{ id:2,label:'二级抗生素(限制使用)',value:'二级抗生素(限制使用)'},
					{ id:3,label:'三级抗生素(特殊使用)',value:'三级抗生素(特殊使用)'},
				],
				highRiskOption:[ // 高危
					{ id:0,label:'非高危药品',value:'非高危药品'},{ id:1,label:' A级高危',value:' A级高危'},{ id:2,label:'B级高危',value:'B级高危'},
					{ id:3,label:'C级高危',value:'C级高危'},
				],
				liquidOptions:[{ id:0,label:'非液体',value:'非液体'},{ id:1,label:'大液体',value:'大液体'},{ id:2,label:'小液体',value:'小液体'}], // 是否液体
				UseOptions:[{ id:0,label:'全部',value:'全部'},{ id:1,label:'门诊',value:'门诊'},{ id:2,label:'其他',value:'其他'}], // 适用范围
				chargedSpcOptions:[{id:0,label:'全部',value:'全部'},{id:1,label:'门诊',value:'门诊'},{id:2,label:'其他',value:'其他'},{id:3,label:'不计费',value:'不计费'}],
				isAntibioticOption:[{id:1,label:'一级抗生素',value:'一级抗生素'},{id:2,label:'二级抗生素',value:'二级抗生素'},{id:3,label:'三级抗生素',value:'三级抗生素'}],
				qualityCategory:[{id:1,label:'一类',value:'一类'},{id:2,label:'二类',value:'二类'},{id:3,label:'三类',value:'三类'}],
				basicTypeOptions:[{ id:1,label:'国家基药',value:'国家基药'},{ id:2,label:'省级基药',value:'省级基药'},{ id:3,label:'地区基药',value:'地区基药'}], //基药类型
				saveOptions:[//储存条件
					{ id:1,label:'常温(0~30°)',value:'常温(0~30°)'},{ id:2,label:'阴凉(2~20°)',value:'阴凉(2~20°)'},
					{ id:3,label:'冷藏(2~8°)',value:'冷藏(2~8°)'},{ id:4,label:'凉暗(2~20°且避光)',value:'凉暗(2~20°且避光)'},
				],
				nurturebOption:[{ id:0,label:'否',value:'否'},{ id:1,label:'普通',value:'普通'},{ id:2,label:'重点',value:'重点'},{ id:3,label:'特殊',value:'特殊'}],
				nurtureOption:[{ id:1,label:'常规养护',value:'常规养护'},{ id:2,label:'重点养护',value:'重点养护'}],
				drugTypeOption:[], //药品类型
				unitDoseOptions:[], //包装单位
				getDosaUntOptions:[], //剂量单位
				expensiveTypeOptions:[{id:1,label:'普价',value:'普价'},{id:2,label:'贵重',value:'贵重'},{id:3,label:'昂贵',value:'昂贵'},{id:4,label:'免费',value:'免费'}],
				medcWayIdOptions:[],//默认给药方式
				usedFrquIdOptions:[],//默认用药频率
				medicationFrequencyOptions:[{ id:1,label:'一日一次',value:'一日一次'},{ id:2,label:'一日三次',value:'一日三次'}],//默认用药频率
				drugDosageOption:[], //ypjx
				drugCategoryOption:[], // yllb I
				drugCategoryChildOption:[], //yllb II
				threeLevelDrugCategoryOption:[], //ypjx
				poisonousTypeOption:[], //dm
				getEisaiOption:[], //卫材类型
				eisaiAtteOption:[{ id:0,label:'普通',value:'普通'},{ id:1,label:'高值',value:'高值'}], //卫材属性
				medicalRecordFeeOption:[], //病案费别
				// drugDosageOption:[], //ypjx
				ManufacturerData:[], //厂家data
				ManufacturerDataRows:[
					{ name:"生产厂家", prop:"manufacturerName", type:"" },{ name:"医保名称", prop:"chsName", type:"" },{ name:"有效状态", prop:"status", type:"" },
					{ name:"药典名称", prop:"pharmacopoeiaName", type:"" },{ name:"产地", prop:"origin", type:"" },
					{ name:"批准文号", prop:"manuLotnum", type:"" },{ name:"药品本位码", prop:"drugCode", type:"" },
					{ name:"自付比例", prop:"ratio", type:"" },{ name:"本地药品", prop:"localDrugs", type:"" },
					{ name:"中标等级", prop:"bidLv", type:"" },{ name:"中标次数", prop:"bidNum", type:"" },
					{ name:"条码值", prop:"barCode", type:"" },{ name:"备注", prop:"remark", type:"" },{ name:"集采中选", prop:"gatherBuyType", type:"" },
					{ name:"网采编码", prop:"netCode", type:"" },{ name:"YPID", prop:"ypid", type:"" }
				], //厂家rows
				boxaBtn:[{ add:"add", title:"", type:"text", icon:"el-icon-plus" },{ adit:"adit", title:"", type:"text", icon:"el-icon-edit" }, { del:"del", title:"", type:"text", icon:"el-icon-delete" }],
				// obj
				editForm:{}, //form提交表单 * 
				param:{},
				res:[],
				elTree:[
					{
						id:1,
						label: '西药',
						title:'西药',
						icon:'el-icon-xy',
					}, 
					{
						id:2,
						label: '中成药',
						title:'中成药',
						icon:'el-icon-zhongchengyao',
					}, 
					{
						id:3,
						label: '卫材',
						title:'卫材',
						icon:'el-icon-zhongcaoyao',
					}, 
					{
						id:4,
						label: '血液',
						title:'血液',
						icon:'el-icon-xyzp',
					}, 
					{
						id:5,
						label: '疫苗',
						title:'疫苗',
						icon:'el-icon-yimiaoke',
					},
				],
				// addRules
				addRules:{
					drugCodeId:[{ required:true,message:'x',trigger:'change' }],
					code:[{ required: true, message: "x", trigger: "change" }],
					name: [{ required: true, message: "x", trigger: "change" }],
					pacUnt: [{ required: true, message: "x", trigger: "blur" }],
					pacCnt: [{ required: true, message: "x", trigger: "blur" }],
					unitDose: [{ required: true, message: "x", trigger: "blur" }],
					dosUnt: [{ required: true, message: "x", trigger: "blur" }],
					minDose: [{ required: true, message: "x", trigger: "blur" }],
					minDoseNum: [{ required: true, message: "x", trigger: "blur" }],
					minUnt: [{ required: true, message: "x", trigger: "blur" }],
				},
				// external
				// props
				//zdy
				
			}
		},
		// life
		mounted() {
			this.editForm = editForm.map(v => {return v })[0]; // Form
			// console.log(this.editForm,'应该传的');
			this.formType = addDialogType.map(v=>{ return v}) // Form
			this.ydName();
		},
		updated() {
			
		},
		methods: {
			/* 数据源 */
			async loadData(){
				this.res = await getDInfo({
					productName:this.inputSearchValue,
					pageNum:this.pageNum,
					pageSize:this.pageSize
				});
				if(this.res.code===200){ 
					this.NameOptions = this.res.data.content.map(v => {return { label: v.productName, ...v}})
				}else{
					this.$message.error(this.res.message)
				}
			},
			/* 编辑 */
			async openeditdialog(param){
				this.dialogFormVisible = true
				console.log(param,'父组件左侧点击树菜单传过来的值')
				// 点击编辑过后将原有的参数组对比浅拷贝的数组进行筛选
				this.editForm = Object.keys(this.editForm).reduce((acc, key) => {
				  if (param.hasOwnProperty(key) && param[key] != null && param[key] !== '') {
				    acc[key] = param[key];
				  } else {
				    acc[key] = this.editForm[key];
				  }
				  return acc;
				}, {});
				// 遍历对象的属性将拿到的整数字符串转换为Number
				for (const key in this.editForm) {
				  if (this.editForm.hasOwnProperty(key)) {
				    const value = this.editForm[key];
				    // 检查是否为整数字符串
				    if (typeof value === 'string' && /^-?\d+$/.test(value.trim())) {
				      this.editForm[key] = Number(value);
				    }
				  }
				}
				
				console.log(this.editForm,'kkkkkkkkkkkkkkkkkk');
				
				this.ManufacturerData = this.editForm.list
				this.getValue = param.drugType //父组件左侧点击树菜单传过来的值
				console.log(this.getValue);
				if(this.getValue === 3){
					// 删除对应的卫材属性不展示eisaiType
					this.formType = this.formType.filter(item => item.id !== 13 && item.id !== 14 && item.id !== 21 && item.id !== 22);	
				}else{
					this.formType = this.formType
				}
				// if(this.getValue )
			},
			// 确定新增
			async editNewDiction(){
				// 自定义赋值
				// this.editForm.code = JSON.parse(sessionStorage.getItem('deptCode'))
				// 	sessionStorage.setItem('itemsForObj', JSON.stringify(this.itemsForObj))
				
				//触发验证表单
				this.$refs.form.validate(async(valid) => {
				if(valid){
				  //验证通过
				  this.editForm.list = this.ManufacturerData;
				  console.log('修改提交',this.editForm);
					let res = await updateDrugInformation(this.editForm)
					if (res.code === 200){
					this.$message({ type: "success", message: res.message });
					// 更新数据驱动
					this.reload();
					// window.location()
					this.dialogFormVisible = false
					}else{
						//验证失败
						this.$message({ type: "error", message: res.message });
					}
				}
				});
			},
			/* props */
			searchMethod(query, option) {
				if(query){
					// console.log('再调一次接口查询');
					this.inputSearchValue = query
					this.pageNum = 0
					this.pageSize = 0
					this.loadData();
				}else{
					this.NameOptions = this.NameOptions
				}
			},
			/* props */
			inputSearch(v,i){
				this.idx = i;
				console.log(i);
				// i event  suffixIcon 为接口
				switch (i) {
					case 0: // 药典名称
						console.log('00000')
					break;
				}
			},
			// select聚焦
			async handlefoucs(v,i){
				this.idx = i;
				console.log(i);
				// i event  suffixIcon 为接口
				switch (i) {
					case 0: // 药典名称 
						this.ydName();
					break;
					case 14:
						this.res = await getDosaUnt();
						if(this.res.code===200){ 
							this.getDosaUntOptions=this.res.data.map(v => {return { label: v.name, ...v}})
						}else{
							this.$message.error(this.res.message)
						}
					break;
					case 18: //包装单位 
						this.res = await getDrugUnt();
						if(this.res.code===200){ 
							this.unitDoseOptions=this.res.data.map(v => {return { label: v.name, ...v}})
						}else{
							this.$message.error(this.res.message)
						}
					break;
					case 27: //药理类别
						this.res = await selectOneCateGory();
						if(this.res.code===200){ 
							this.drugCategoryOption=this.res.data
						}
					break;
					case 28: //药理类别2
						this.res = await selectTwoCateGory({idcode:this.idcode});
						if(this.res.code===200){ 
							this.drugCategoryChildOption=this.res.data
						}
					break;
					case 29: //药理类别3
						this.res = await selectThreeCateGory({idcode:this.idcode});
						if(this.res.code===200){ 
							this.threeLevelDrugCategoryOption=this.res.data
						}
					break;
					case 31: //默认给药方式
						this.res = await getMedicationFrequency();
						if(this.res.code===200){ 
							this.medcWayIdOptions=this.res.data.map(v => {return { label: v.name, ...v}})
						}
					break;
					case 32: //默认用药频率
						this.res = await getMedicationWay();
						if(this.res.code===200){ 
							this.usedFrquIdOptions=this.res.data.map(v => {return { label: v.name, ...v}})
						}
					break;
					case 46: //卫材
						this.res = await getEisai();
						if(this.res.code===200){ 
							this.getEisaiOption=this.res.data.map(v => {return { label: v.name, ...v}})
						}
					break;
					case 55: //毒麻
						this.res = await selectDocVtByType();
						if(this.res.code===200){ 
							this.poisonousTypeOption=this.res.data.map(v => {return { label: v.name, ...v}})
						}
					break;
					case 60: //病案费别
						this.res = await getMedcas();
						if(this.res.code===200){ 
							this.medicalRecordFeeOption=this.res.data.map(v => {return { label: v.name, ...v}})
						}
					break;
				}
			},
			/*  接口 */
			async ydName(){ //药典名称
				this.res = await getDInfo({
					pageNum:this.pageNum,
					pageSize:this.pageSize
				});
				if(this.res.code===200){ 
					this.NameOptions = this.res.data.content.map(v => {return { label: v.productName, ...v}})
				}else{
					this.$message.error(this.res.message)
				}
			},
			// selectChance
			handleChange(val){
				console.log(val,this.idx);
				switch (this.idx) {
					case 0:
					// 根据 NameOptions绑定的id 找到对应的对象
					let nameObj = this.NameOptions.find(name => name.id === val)
					console.log(nameObj);
					this.editForm.code = nameObj.drugCode; //编码
					this.editForm.drugCodeId = nameObj.id;
					this.editForm.drugCodeName = nameObj.productName; //药典名
					this.editForm.dosform = nameObj.dosageForm; //剂型
					this.editForm.drugSpec = nameObj.specifications; //规格
					this.editForm.drugName = nameObj.productName; //名称
					this.editForm.pyCode = this.makePy(nameObj.productName).toUpperCase(); //名称简码
					break;
					case 23: //基本药物
					if(this.editForm.basMedn == 0){
						this.addDisabled = true
						this.editForm.basMednType = ''
					}else{
						this.addDisabled = false
					} 
					break;
					case 27: //药理类别
					if(this.editForm.phamType1){
						// 根据 NameOptions绑定的id 找到对应的对象
						let phamObj = this.drugCategoryOption.find(name => name.id === val)
						this.idcode = phamObj.idcode
						this.addDisabled = false
					}else{
						this.addDisabled = true
						this.editForm.basMednType = ''
					} 
					// .map(v => {return { label: v.name, ...v}})
					break;
					case 28: //药理类别II
					if(this.editForm.phamType1){
						// 根据 NameOptions绑定的id 找到对应的对象
						let phamObj2 = this.drugCategoryChildOption.find(name => name.id === val)
						this.idcode = phamObj2.idcode
						this.addDisabled = false
					}else{
						this.addDisabled = true
						this.editForm.basMednType = ''
					} 
					// .map(v => {return { label: v.name, ...v}})
					break;
					// case 10:
					// let idcode3 = this.editForm.threeLevelDrugCategory
					// this.idcode = this.threeLevelDrugCategoryOption.filter(item => item.id === idcode3)[0].idcode;
					// this.editForm.threeLevelDrugCategoryName = this.threeLevelDrugCategoryOption.filter(item => item.id === idcode3)[0].label;
					// break;
					// case 14:
					// this.editForm.isAntibiotic == 1 ? this.disabledKss = false : this.disabledKss = true;
					// this.editForm.antibioticLevel == ''
					// break;
				}
			},
			// input失焦 简码转换赋值
			inputChance(v,i){
				// i event
				switch (i) {
					case 8:  // 通用名失焦开始赋值
					this.editForm.alisPyCode = this.makePy(this.editForm.alis).toUpperCase()
					break;
				}
			},
			// son btn events
			boxaBtnHandClick(i){
				// i event
				switch (i) {
					case 0:
						// 处理索引0的逻辑
						// this.addManufacturerDiglog = true;
						// this.editMTitle = '新增厂家信息';
						// this.listCharge = {};
						// this.Namedisabled = false;
						this.addDialogManufacturer = true;
						break;
					case 1:
						// 处理索引1的逻辑  => 打开编辑厂家model
						this.$refs.editComponent.openEditModel(this.ManufacturerData);
						// 直接调用子组件的方法，并传递参数
						break;
					case 2:
						// 处理索引2的逻辑 => 新增
						console.log('删除')
				}
			},
			// 控制厂家新增model，接收子组件传递过来的值并赋值
			Manufacturer(newVal){
				this.addDialogManufacturer = false;
				console.log(newVal,'子组件传过来的');
				this.ManufacturerData.push(JSON.parse(JSON.stringify(newVal)))
			},
			// 控制厂家修改model，接收子组件传递过来的值并赋值
			editManufacturer(newVal){
				this.addDialogManufacturer = false;
				console.log(newVal,'修改子组件传过来的');
				this.ManufacturerData=[]; //先清空
				this.ManufacturerData.push(JSON.parse(JSON.stringify(newVal)))
			},
			// 时间处理
			changDate(val){
				let i = this.idx
				switch(i) {
					case 5:
					function formatDate(date) {
					  const year = date.getFullYear();
					  const month = (date.getMonth() + 1).toString().padStart(2, '0');
					  const day = date.getDate().toString().padStart(2, '0');
					  return `${year}-${month}-${day}`;
					}
					 
					// 使用示例
					const now = new Date();
					this.editForm.dateOfEmp = formatDate(val);
				}
			},
			// 地区处理
			handleSelectCost(val) {
			  this.editForm.nativePlace = val.join(',')
			},
			// 关闭Model
			handleAddClose(done){
				this.reload();
				done();
			},
			
		},

	}
</script>

<style lang="less" scoped>
	/deep/ .el-select-dropdown__item {
		height: 36px;
		line-height: 14px;
		display: flex;
		align-items: center;
	}
.content{
	height: 100%;
	width: 100%;
	.header{
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #007bb0;
		padding: 4px;
	}
	.main{
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		
	}
}
</style>